﻿using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Folding;
using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using System.IO;
using System.Data;
using NPOI.HSSF.UserModel;

namespace NB_Controller_Test
{
    /// <summary>
    /// ScnControlUI.xaml 的交互逻辑
    /// </summary>
    public partial class MainUIEx : UserControl
    {
        private UdpDataSndRecv udpDataRecv;

        private FoldingManager foldingManager_tbSndMsgData = null;
        private FoldingManager foldingManager_tbRecvMsgData = null;
        private FoldingManager foldingManager_tbSndReMsgData = null;
        private AbstractFoldingStrategy foldingStrategy_tbSndMsgData = new BraceFoldingStrategy();
        private AbstractFoldingStrategy foldingStrategy_tbRecvMsgData = new BraceFoldingStrategy();
        private AbstractFoldingStrategy foldingStrategy_tbSndReMsgData = new BraceFoldingStrategy();

        SignalDataManger sdMng = new SignalDataManger();
        List<Color> colorList = new List<Color>();

        private IniFiles iniFile = new IniFiles("SysConfig.ini");

        public MainUIEx()
        {
            /*
             * 
             * NB开发板led闪烁说明：
                每隔10s快闪1下，NB在测试模式
                每隔10s快闪2下，NB在初始化
                每隔10s快闪3下，NB在附着网络
                每隔10s快闪4下，NB在获取IP地址
                每隔10s快闪5下，NB附着网络成功
                每隔10s快闪6下，NB异常
                每隔10s快闪7下，NB升级模式
             * */
            InitializeComponent();

            InitWpfChart();

            //InitCmdBut();

            InitLogList();

            InitDataTable();

            //使用内置文件服务器
            StartHttpServer();

            InitEventLog();

            //判断是否需要显示GPRS相关
            if (cbShowGPRSInfo.IsChecked == true)
            {
                //显示
                spGPRSInfo.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                //隐藏
                spGPRSInfo.Visibility = System.Windows.Visibility.Collapsed;
            }

            //ContentType
            typeManager.LoadXmlConfig("ContentTypeConfig.xml");
            cbContentType.Items.Clear();
            foreach (ContentType type in typeManager.contentTypeList)
            {
                ComboBoxItem itemType = new ComboBoxItem();
                itemType.Content = type.StrTypeName;

                cbContentType.Items.Add(itemType);
            }
            if (cbContentType.Items.Count > 0)
            {
                cbContentType.SelectedIndex = 0;
            }

            //srcIP
            ComboBoxItem itemIP;// = new ComboBoxItem();
            List<string> strIPs = GlobalFun.GetIPAddress();
            foreach (string strIP in strIPs)
            {
                itemIP = new ComboBoxItem();
                itemIP.Content = strIP;
                srcIP.Items.Add(itemIP);
            }
            srcIP.SelectedIndex = 0;
            hfsIP.Text = srcIP.Text;

            //恢复
            string strIPRead = iniFile.ReadValue("OTAConfig", "OTA_IP", hfsIP.Text);
            string strPortRead = iniFile.ReadValue("OTAConfig", "OTA_Port", hfsPort.Text);
            string strBinFileRead = iniFile.ReadValue("OTAConfig", "OTA_BinFile", tbOTABinFile.Text);
            string strVerRead = iniFile.ReadValue("OTAConfig", "OTA_Ver", tbOTABinFileVer.Text);

            hfsIP.Text = strIPRead;
            hfsPort.Text = strPortRead;//80
            tbOTABinFile.Text = strBinFileRead;
            tbOTABinFileVer.Text = strVerRead;

            //devIP
            itemIP = new ComboBoxItem();
            itemIP.Content = "0.0.0.0（广播）";
            itemIP.Tag = IntPtr.Zero;
            devIP.Items.Add(itemIP);

            devIP.SelectedIndex = 0;

            //UDPDataRecv
            udpDataRecv = UdpDataSndRecv.GetUdpDataRecv(this);
            udpDataRecv.RegisterRecvMsgProc(HandleUdpRecvMsg);

            //HightLight
            //以下设置，若被包含在父控件中，设置无法马上奇效果，原因不明.
            //tbSndMsgDataCbHightLight.Text = "JavaScript";
            //tbRecvMsgDataCbHightLight.Text = "C#";
            //tbSndReMsgDataCbHightLight.Text = "C++";

            //自动更新显示折叠大纲定时器
            systemTimer = new DispatcherTimer();
            systemTimer.Interval = TimeSpan.FromSeconds(0.333f);
            systemTimer.Tick += systemTimer_Tick;
            //初始化完毕再启动
            //systemTimer.Start();

            //
            string strOTA_TimeOutTime = GlobalFun.GetAppConfigValue("OTA_TimeOutTime");
            uiOTA_TimeOutTime = GlobalFun.StringToUInt16(strOTA_TimeOutTime);

            string strCan_Config = GlobalFun.GetAppConfigValue("Can_Config");
            uiCanConfig = GlobalFun.StringToUInt16(strCan_Config);

            if(uiCanConfig == 0)
            {
                //只保留OTA相关功能
                //快捷命令禁用
                svCmd.IsEnabled = false;
                //发送编辑框禁用
                tbSndMsgData.IsEnabled = false;
                //发送按钮禁用
                tbCmdName.IsEnabled = false;
                btQuickCmd.IsEnabled = false;
                butSend.IsEnabled = false;

                gridReadInfo.IsEnabled = false;
                gridSend.IsEnabled = false;

                cbShowGPRSInfo.IsEnabled = false;

                //判断当前时间，若时间大于2019-6-15则不让使用
                DateTime dateTime = DateTime.Now;
                string strValid_Data1 = GlobalFun.GetAppConfigValue("Valid_Data1");
                UInt16 usValid_Data1 = GlobalFun.StringToUInt16(strValid_Data1);
                string strValid_Data2 = GlobalFun.GetAppConfigValue("Valid_Data2");
                UInt16 usValid_Data2 = GlobalFun.StringToUInt16(strValid_Data2);
                string strValid_Data3 = GlobalFun.GetAppConfigValue("Valid_Data3");
                UInt16 usValid_Data3 = GlobalFun.StringToUInt16(strValid_Data3);
                //故意减去10，系统配置时故意增加10
                DateTime dateInvalidTime = new DateTime(2000 + usValid_Data3 - 10, usValid_Data2 - 10, usValid_Data1 - 10);
                if(dateTime > dateInvalidTime)
                {
                    MessageBox.Show("软件超期，无使用权限！请联系相关人员。");
                    //this.IsEnabled = false;
                    Environment.Exit(0);
                    return;
                }
            }
            else
            {
                //保留全部功能
            }

            //启动系统定时器
            systemTimer.Start();
        }

        private void StartHttpServer()
        {
            UInt16 usPort = GlobalFun.StringToUInt16(hfsPort.Text);
            GlobalFun.StartHttpServer(this, usPort);
        }

        public void ExitMainUIEx()
        {
            systemTimer.Stop();

            //做一些后续工作
            //先根据当前的顺序对快捷命令排序
            //Button butCmd = (Button)mdThumb.Template.FindName("Button", mdThumb);
            //Button butCoverCmd = (Button)lastThumb.Template.FindName("Button", lastThumb);
            sendCmds.SortSendCmdsByNames(thumbList);


            sendCmds.Save();
            devAliasNames.Save();
            systemConfig.Save();

            UninitDataTable();
        }

        private string strPCMarkBegin = "PCMarkBegin";
        private string strPCMarkEnd = "PCMarkEnd";
        public void HandleUdpRecvMsg(object obj, Byte byType)
        {
            SendRecvData recvData = obj as SendRecvData;

            TextEditor tb = tbRecvMsgData;
            if (byType == 1)
                tb = tbSndReMsgData;

            //超过一万行自动清空，防止界面卡顿
            if (tb.LineCount > 1 * 10000)
                tb.Text = "";

            //根据协议格式除了中间Json为ASCII外其他格式化为16进制数据
            string strData = GlobalFun.ByteArrayToString(recvData.byData, Encoding.ASCII);
            string strBinaryData = GlobalFun.ByteArrayToHexString(recvData.byData, recvData.byData.Length, " ");
            string strTime = DateTime.Now.ToString("HH:mm:ss fff ");
            System.Diagnostics.Debug.Write(strTime + " [Recv] \r\n [Binary] " + strBinaryData);

            //IP Port解析
            string strIP = "";
            UInt16 uiPort = 0;
            NetLink.GetNetLink().udpServerController.GetIPAndPortByConnId(recvData.connId, ref strIP, ref uiPort);

            //先判断是否是其他工具转发过来的
            int nPCMarkBeginInx = strData.IndexOf(strPCMarkBegin);
            int nPCMarkEndInx = strData.IndexOf(strPCMarkEnd);
            if (nPCMarkBeginInx < nPCMarkEndInx)
            {
                //PC的转发
                //将带过来的IP信息覆盖当前的IP信息
                string strConnID = strData.Substring(strPCMarkBegin.Length, nPCMarkEndInx - strPCMarkBegin.Length);
                UInt16 uiConnID = GlobalFun.StringToUInt16(strConnID);
                recvData.connId = (IntPtr)(uiConnID);

                nPCMarkEndInx += strPCMarkEnd.Length;
            }
            //else
            {
                if (nPCMarkEndInx == -1)
                    nPCMarkEndInx = 0;

                //这里假定第一个{出现的序号后面的都是JSon 数据，其实是不合理的。
                int nJsonStartInx = strData.IndexOf("{");
                if (nJsonStartInx > 0)
                {
                    #region 协议解析
                    int nHeadLen = Marshal.SizeOf(NB_Protocol.NB_PROT_HEAD_FLAG);
                    int nHeadProlLen = (1 + 1 + 2 + 2) + (4 + 1 + 1);
                    int nTailLen = Marshal.SizeOf(NB_Protocol.NB_PROT_TAIL_FLAG);
                    Byte[] byHeadData = new Byte[nHeadLen];
                    Array.Copy(recvData.byData, 0 + nPCMarkEndInx, byHeadData, 0, nHeadLen);

                    //下面的大小与NB_Protocol协议定义存在关联，后续修改要注意
                    Byte[] byHeadProlData = new Byte[nHeadProlLen];
                    Array.Copy(recvData.byData, nHeadLen + nPCMarkEndInx, byHeadProlData, 0, nHeadProlLen);


                    Byte[] byJsonData = new Byte[recvData.byData.Length - nPCMarkEndInx - nHeadLen - nHeadProlLen - nTailLen];
                    Array.Copy(recvData.byData, nHeadLen + nHeadProlLen + nPCMarkEndInx, byJsonData, 0, byJsonData.Length);

                    Byte[] byEndData = new Byte[nTailLen];
                    Array.Copy(recvData.byData, recvData.byData.Length - nTailLen, byEndData, 0, nTailLen);

                    string strHeadData = GlobalFun.ByteArrayToHexString(byHeadData, byHeadData.Length, " ") + "\r\n";
                    string strHeadProlData = GlobalFun.ByteArrayToHexString(byHeadProlData, byHeadProlData.Length, " ") + "\r\n";
                    string strJsonData = GlobalFun.ByteArrayToString(byJsonData, Encoding.ASCII);
                    string strEndData = GlobalFun.ByteArrayToHexString(byEndData, byEndData.Length, " ") + "\r\n";
                    #endregion

                    //NB_Protocol nb_Prol = NB_Protocol.CreateNew(strHeadData, strHeadProlData, strJsonData, strEndData);
                    //添加进接收队列
                    //nb_ProlManger.recvList.Add(nb_Prol);

                    string strSeqNumValue = strHeadProlData.Substring((1 + 1 + 2 + 2) * 3, 4 * 3);
                    strSeqNumValue = "0x" + strSeqNumValue.Replace(" ", "");
                    UInt32 ulSeqNum = GlobalFun.HexStringToUInt32(strSeqNumValue);

                    //考虑缓存SeqNum???命令回复时考虑上次下发的SeqNum
                    //根据SeqNum判断是否是针对本工具的命令回复
                    //获取当前IP
                    string strIPLocal = srcIP.Text;
                    strIPLocal = strIPLocal.Substring(strIPLocal.LastIndexOf('.') + 1);
                    UInt16 uiIP = GlobalFun.StringToUInt16(strIPLocal);
                    //组合成SeqNum
                    //UInt32 unSeqNum = (UInt32)((uiIP << 16) + 0x0001);

                    UInt16 uiIPRecv = (UInt16)(ulSeqNum >> 16);
                    if (uiIP == uiIPRecv)
                    {
                        //针对本机的命令回复
                    }
                    else
                    {
                        //针对他机的命令回复，需要转发
                        #region
                        strIPLocal = srcIP.Text;
                        //替换最后一个字节
                        strIPLocal = strIPLocal.Substring(0, strIP.LastIndexOf('.') + 1);

                        //0x00表示旧版本的调试工具，那么需要广播转发？？？
                        if (uiIPRecv == 0x00)
                        {
                            //uiIPRecv = 0xff;
                            //return;//先忽略吧
                            //暂时先认为是本机的数据包，继续处理
                            System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss fff ") + " [Recv] SeqNum:" + strSeqNumValue);
                        }
                        else
                        {
                            strIPLocal += uiIPRecv.ToString();
                            strIPLocal = strIPLocal + ":" + NetLink.LOCAL_PORT.ToString();

                            //信息转发给他机
                            //string strIPLocal = "10.10.70.22:65002";
                            //string strPCMarkBegin = "PCMarkBegin";
                            //string strPCMarkEnd = "PCMarkEnd";
                            string strConnID = recvData.connId.ToString();
                            Byte[] byPCMarkDatas = GlobalFun.StringToByteArray(strPCMarkBegin + strConnID + strPCMarkEnd, Encoding.ASCII);
                            Byte[] byAllDatas = new Byte[byPCMarkDatas.Length + recvData.byData.Length];
                            Array.Copy(byPCMarkDatas, 0, byAllDatas, 0, byPCMarkDatas.Length);
                            Array.Copy(recvData.byData, 0, byAllDatas, byPCMarkDatas.Length, recvData.byData.Length);
                            NetLink.GetNetLink().SendMsgByIP(strIPLocal, byAllDatas, 0, byAllDatas.Length);

                            return;
                        }
                        #endregion
                    }

                    //判断回复的数据是否需要进入统计
                    if (cbCountQuickCmd.IsChecked == true)
                    {
                        string strSeqNum = strHeadProlData.Substring(18, 11);
                        foreach (DataRow row in dataTable_QuickCmd.Rows)
                        {
                            if (row.RowError == strSeqNum)
                            {
                                //更新最后一列单元格的数据
                                if (byType == 0)
                                {
                                    row.SetField(5, DateTime.Now.ToString());
                                    row.SetField(6, strJsonData);
                                }
                            }
                        }
                    }

                    //第一次扫描时显示，后续不再显示
                    bool bShouldShowInUI = true;
                    //数据对应到UI
                    #region
                    try
                    {
                        Newtonsoft.Json.Linq.JObject jObj = Newtonsoft.Json.Linq.JObject.Parse(strJsonData);
                        //除去多余无效\r\n以及空格
                        strJsonData = jObj.ToString();

                        JToken jtProp = jObj.GetValue("prop");
                        if (jtProp != null && byType != 1)
                        {
                            bShouldShowInUI = AnalysisJToken(recvData.connId, jtProp);
                        }

                        JToken jtItems = jObj.GetValue("items");
                        if (jtItems != null && byType != 1)
                        {
                            DoLogItems(recvData.connId, jtItems);
                        }

                        JToken jtCmdId = jObj.GetValue("cmdId");
                        if (jtCmdId != null && byType != 1)
                        {
                            //JToken jtCmdData = jObj.GetValue("cmdData");
                            DoOTAUDP(recvData.connId, jObj);
                        }

                        //判断是否是开始OTA返回错误信息
                        /*
                         * 
                         * {
                              "reqId": 41,
                              "err": 513,
                              "errDesc": "OTA clas or sku error",
                              "cmdId": "OTAUDP"
                            }
                         * */
                        JToken jtError = jObj.GetValue("err");
                        JToken jtErrorDesc = jObj.GetValue("errDesc");
                        if ((jtError != null && jtError.ToString() == "513") && (jtErrorDesc != null && jtErrorDesc.ToString().Contains("error")))
                        {
                            DoStopOTAUDP(recvData.connId);
                        }

                    }
                    catch (Newtonsoft.Json.JsonReaderException e)
                    {
                        e = e;
                    }

                    if (bShouldShowInUI)
                    {
                        tb.Text += ("//" + strTime + " [" + strIP + " : " + uiPort.ToString() + "] \r\n" + strHeadData + strHeadProlData + strJsonData + "\r\n" + strEndData) + "\r\n";
                    }

                    //System.Diagnostics.Debug.Write("\r\n [Format] " + strHeadData + strJsonData + strEndData);
                    #endregion
                }
                else
                {
                    tb.Text += ("//" + strTime + " [" + strIP + " : " + uiPort.ToString() + "] \r\n" + strData) + "\r\n";
                }

                //System.Diagnostics.Debug.Write("\r\n");

                //自动滚动到底部
                tb.ScrollToEnd();

                //协议数据格式化处理
                #region
                if (foldingStrategy_tbSndMsgData != null && foldingManager_tbSndMsgData != null)
                {
                    foldingStrategy_tbSndMsgData.UpdateFoldings(foldingManager_tbSndMsgData, tbSndMsgData.Document);
                }

                if (foldingStrategy_tbRecvMsgData != null && foldingManager_tbRecvMsgData != null)
                {
                    foldingStrategy_tbRecvMsgData.UpdateFoldings(foldingManager_tbRecvMsgData, tbRecvMsgData.Document);
                }

                if (foldingStrategy_tbSndReMsgData != null && foldingManager_tbSndReMsgData != null)
                {
                    foldingStrategy_tbSndReMsgData.UpdateFoldings(foldingManager_tbSndReMsgData, tbSndReMsgData.Document);
                }
                #endregion
            }
        }

        public void SwitchOTADownProgress(string strIP, UInt16 usProgress)
        {
            strIP = strIP.Substring(0, strIP.IndexOf(":"));
            //System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " strIP ：" + strIP + " 进度: " + (usProgress).ToString());

            //只是不支持进度的版本才用这个进度
        }

        private UInt16 uiOTA_TimeOutTime = 30;
        private UInt64 ulSystemTickTimes = 0;
        //是否支持可配置命令，默认不支持（只保留OTA相关功能）
        private UInt16 uiCanConfig = 0;
        private DispatcherTimer systemTimer;
        private SolidColorBrush sbVerOK = new SolidColorBrush(Colors.Transparent);
        private SolidColorBrush sbVerError = new SolidColorBrush(Colors.MistyRose);
        private SolidColorBrush sbIMEICheck = new SolidColorBrush(Colors.LightBlue);
        private void systemTimer_Tick(object sender, EventArgs se)
        {
            ulSystemTickTimes++;

            if (ulSystemTickTimes == 1)
            {
                InitCmdBut();

                #region 代码格式化控件处理
                tbSndMsgDataCbHightLight.Text = "JavaScript";
                //tbSndMsgDataCbHightLight1.Text = "JavaScript";
                tbRecvMsgDataCbHightLight.Text = "C#";
                tbSndReMsgDataCbHightLight.Text = "C++";

                if (foldingStrategy_tbSndMsgData != null)
                {
                    foldingStrategy_tbSndMsgData.UpdateFoldings(foldingManager_tbSndMsgData, tbSndMsgData.Document);
                }

                //if (foldingStrategy_tbSndMsgData1 != null)
                //{
                //    foldingStrategy_tbSndMsgData1.UpdateFoldings(foldingManager_tbSndMsgData1, tbSndMsgData1.Document);
                //}

                if (foldingStrategy_tbRecvMsgData != null)
                {
                    foldingStrategy_tbRecvMsgData.UpdateFoldings(foldingManager_tbRecvMsgData, tbRecvMsgData.Document);
                }

                if (foldingStrategy_tbSndReMsgData != null)
                {
                    foldingStrategy_tbSndReMsgData.UpdateFoldings(foldingManager_tbSndReMsgData, tbSndReMsgData.Document);
                }
                #endregion
            }

            #region 自动扫描设备--OTA后确认版本用，废弃
            //if (bAutoSendScanCmd)
            //{
            //    //uiOTATimes++;
            //    #region
            //    //5秒获取一次当前版本
            //    //if (uiSystemTickTimes % (3 * 5) == 0)
            //    {
            //        //foreach (DevItemView devItem in lvDevList.Children)
            //        //{
            //        //    if (devItem.checkOTA.IsChecked == true && devItem.pbOTAing.Visibility == System.Windows.Visibility.Visible)
            //        //    {
            //        //        IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
            //        //        bool bOK = SendRequreVerCmd(intPtr);
            //        //    }
            //        //}

            //        //清除掉
            //        //lvDevList.Children.Clear();

            //        //bAutoCleanDevList = false;
            //    }
            //    #endregion
            //    #region
            //    //10秒获取一次当前版本
            //    //if (uiOTATimes % 10 == 0)
            //    //{
            //    //    foreach (DevItemView devItem in lvLines.Items)
            //    //    {
            //    //        if (devItem.checkOTA.IsChecked == true && devItem.pbOTAing.Visibility == System.Windows.Visibility.Visible)
            //    //        {                            
            //    //            if (uiOTATimes % 20 == 0)
            //    //            {
            //    //                //每20秒再发一次OTA命令
            //    //                IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
            //    //                string strIP = hfsIP.Text;// "192.168.10.99";
            //    //                bool bOK = SendOTACmd(strIP, intPtr);
            //    //            }

            //    //            if (uiOTATimes >= 5 * 60)
            //    //            {
            //    //                //判断是否超时 默认认为5分钟超时
            //    //                devItem.SetOTAState(DevItemView.byOTATimeout);
            //    //                bAutoCheckOTADone = false;
            //    //            }
            //    //            else
            //    //            {
            //    //                IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
            //    //                bool bOK = SendRequreVerCmd(intPtr);
            //    //            }
            //    //        }
            //    //    }
            //    //}
            //    #endregion                                

            //    //3S
            //    if (uiSystemTickTimes % (3 * 3) == 0 && lbOTASuccessedInfo.Tag != null)
            //    {
            //        int nOTADoneSize = 0;
            //        foreach (DevItemView devItem in lvDevList.Children)
            //        {
            //            if (devItem.ver.Text == tbOTABinFileVer.Text)
            //            {
            //                nOTADoneSize++;
            //            }
            //        }

            //        int nLastOTASize = GlobalFun.StringToUInt16(lbOTASuccessedInfo.Tag.ToString());

            //        //扫描到的数量与记忆数量一致，则停止扫描
            //        if (nLastOTASize == nOTADoneSize)
            //        {
            //            lbOTASuccessedInfo.Tag = null;
            //            bAutoSendScanCmd = false;
            //        }
            //        else
            //        {
            //            //执行重新扫描动作
            //            SendGetDevInfoCmd(IntPtr.Zero);
            //        }
            //    }
            //}
            #endregion

            #region 0.333 * 3秒获取一次
            if (ulSystemTickTimes % (3) == 0)
            {
                //bool bShowCurVer = cbCheckVer.IsChecked == true;

                int nTotalSize = lvDevList.Children.Count + lvDevList1.Children.Count + lvDevList2.Children.Count + lvDevList3.Children.Count + lvDevList4.Children.Count;
                #region 设备版本与预期版本匹配个数
                UInt16 usOTADoneSize = 0;
                foreach (DevItemView devItem in lvDevList.Children)
                {
                    //版本确认逻辑
                    DoVerCheck(devItem, ref usOTADoneSize);                    

                    //开始执行OTA的设备，主动询问当前进度
                    DoCheckOTAStatus(devItem);

                    #region 确认与输入的IMEI是否一致，一致则高亮
                    if (devItem.imei.Text == tbIMEIFilter.Text)
                    {
                        devItem.Background = sbIMEICheck;
                    }
                    else
                    {
                        //
                    }
                    #endregion
                }

                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    //版本确认逻辑
                    DoVerCheck(devItem, ref usOTADoneSize);

                    //开始执行OTA的设备，主动询问当前进度
                    DoCheckOTAStatus(devItem);

                    #region 确认与输入的IMEI是否一致，一致则高亮
                    if (devItem.imei.Text == tbIMEIFilter.Text)
                    {
                        devItem.Background = sbIMEICheck;
                    }
                    else
                    {
                        //
                    }
                    #endregion
                }

                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    //版本确认逻辑
                    DoVerCheck(devItem, ref usOTADoneSize);

                    //开始执行OTA的设备，主动询问当前进度
                    DoCheckOTAStatus(devItem);

                    #region 确认与输入的IMEI是否一致，一致则高亮
                    if (devItem.imei.Text == tbIMEIFilter.Text)
                    {
                        devItem.Background = sbIMEICheck;
                    }
                    else
                    {
                        //
                    }
                    #endregion
                }

                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    //版本确认逻辑
                    DoVerCheck(devItem, ref usOTADoneSize);

                    //开始执行OTA的设备，主动询问当前进度
                    DoCheckOTAStatus(devItem);

                    #region 确认与输入的IMEI是否一致，一致则高亮
                    if (devItem.imei.Text == tbIMEIFilter.Text)
                    {
                        devItem.Background = sbIMEICheck;
                    }
                    else
                    {
                        //
                    }
                    #endregion
                }

                 foreach (DevItemView devItem in lvDevList4.Children)
                {
                    //版本确认逻辑
                    DoVerCheck(devItem, ref usOTADoneSize);

                    //开始执行OTA的设备，主动询问当前进度
                    DoCheckOTAStatus(devItem);

                    #region 确认与输入的IMEI是否一致，一致则高亮
                    if (devItem.imei.Text == tbIMEIFilter.Text)
                    {
                        devItem.Background = sbIMEICheck;
                    }
                    else
                    {
                        //
                    }
                    #endregion
                }

                //lbOTASuccessedInfo.Content = "OTA/总数 : " + nOTADoneSize.ToString() + "/" + nTotalSize.ToString();
                lbOTASuccessedInfo.Content = tbOTABinFileVer.Text + "/总数 : " + usOTADoneSize.ToString() + "/" + nTotalSize.ToString();
                #endregion
            }

            #endregion

            if (bDoCheckOnline == true)
            {
                #region
                if (ulSystemTickTimes - ulCheckOnlineTimes > 6)
                    bDoCheckOnline = false;

                //每秒一次更新设备条目当前在线离线状态
                foreach (DevItemView devItem in lvDevList.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGray);

                        //设备在线检测阶段，这里再次单播询问是否在线
                        SendGetWifiInfoCmd((IntPtr)devItem.Tag);
                    }
                    else
                    {
                        devItem.Background = new SolidColorBrush(Colors.Transparent);
                    }
                }

                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGray);

                        //设备在线检测阶段，这里再次单播询问是否在线
                        SendGetWifiInfoCmd((IntPtr)devItem.Tag);
                    }
                    else
                    {
                        devItem.Background = new SolidColorBrush(Colors.Transparent);
                    }
                }

                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGray);

                        //设备在线检测阶段，这里再次单播询问是否在线
                        SendGetWifiInfoCmd((IntPtr)devItem.Tag);
                    }
                    else
                    {
                        devItem.Background = new SolidColorBrush(Colors.Transparent);
                    }
                }

                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGray);

                        //设备在线检测阶段，这里再次单播询问是否在线
                        SendGetWifiInfoCmd((IntPtr)devItem.Tag);
                    }
                    else
                    {
                        devItem.Background = new SolidColorBrush(Colors.Transparent);
                    }
                }

                foreach (DevItemView devItem in lvDevList4.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGray);

                        //设备在线检测阶段，这里再次单播询问是否在线
                        SendGetWifiInfoCmd((IntPtr)devItem.Tag);
                    }
                    else
                    {
                        devItem.Background = new SolidColorBrush(Colors.Transparent);
                    }
                }
                #endregion
            }

            if (bAutoFitToView)
            {
                #region
                bAutoFitToView = false;
                signlRecord_rsrp.Viewport.FitToView();
                signlRecord_txpower.Viewport.FitToView();
                signlRecord_snr.Viewport.FitToView();
                signlRecord_cellID.Viewport.FitToView();
                signlRecord_rssi.Viewport.FitToView();
                #endregion
            }
        }

        private double dChartTimes = 0;
        private DispatcherTimer chartTimer;
        private void chartTimer_Tick(object sender, EventArgs se)
        {
            if (bAutoSendRssiCmd)
            {
                dChartTimes += 1;// (UInt16)chartTimer.Tag;

                string strScan = "{\"reqId\": 40,\"op\": \"R\",\"prop\": [\"nbSignal\"]}";
                bool bOK = SendMsgNeedJSonBody(strScan, IntPtr.Zero);

                strScan = "{\"reqId\": 40,\"op\": \"R\",\"prop\": [\"apInfo\"]}";
                bOK = SendMsgNeedJSonBody(strScan, IntPtr.Zero);
            }
        }

        private UInt16 uiSendMsgTimes = 0;
        private DispatcherTimer reTimesTimer;
        private void reTimesTimer_Tick(object sender, EventArgs e)
        {
            uiSendMsgTimes -= 1;
            lbTimes.Content = uiSendMsgTimes.ToString() + " / " + tbReTimes.Text;

            if (uiSendMsgTimes == 0)
            {
                reTimesTimer.Stop();
                reTimesTimer = null;
                butSend.IsEnabled = true;
                lbTimes.Content = "发送完毕！";
            }
            else
            {
                ButSendMsg_Click(null, null);
            }
        }

        private void cbContentType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            ComboBoxItem item = cb.SelectedItem as ComboBoxItem;

            string strText = string.Empty;
            if (item != null)
            {
                strText = item.Content.ToString();
            }
            //更新当前
            ContentType contType = new ContentType();
            contType.StrProlID = tbProlID.Text;
            contType.StrProlVer = tbProlVer.Text;
            contType.StrIsRsp = tbIsRsp.Text;
            contType.StrTypeJsonBody = tbSndMsgData.Text;
            //contType.StrTypeJsonBody1 = tbSndMsgData1.Text;
            typeManager.UpdateByName(cb.Text, contType);

            //反查
            tbSndMsgData.Text = "";
            //tbSndMsgData1.Text = "";
            contType = typeManager.FindJsonBodyByName(strText);
            if (contType != null)
            {
                tbProlID.Text = contType.StrProlID;
                tbProlVer.Text = contType.StrProlVer;
                tbIsRsp.Text = contType.StrIsRsp;
                tbSndMsgData.Text = contType.StrTypeJsonBody;
                //tbSndMsgData1.Text = contType.StrTypeJsonBody1;
            }
        }

        #region 代码格式化控件处理
        private void ButClrRecvMsg_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要清空？", "警告", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                tbRecvMsgData.Text = "";
        }

        private void ButShowLogTimeLine_Click(object sender, RoutedEventArgs e)
        {
            LogTimeLineWnd logWnd = new LogTimeLineWnd();
            logWnd.Show();
        }

        private void ButClrSendMsg_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要清空？", "警告", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                tbSndReMsgData.Text = "";
        }

        private void tbSndMsgDataHighlightCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tbSndMsgData.SyntaxHighlighting == null)
            {
                foldingStrategy_tbSndMsgData = null;
            }
            else
            {
                switch (tbSndMsgData.SyntaxHighlighting.Name)
                {
                    case "XML":
                        foldingStrategy_tbSndMsgData = new XmlFoldingStrategy();
                        break;
                    case "C#":
                    case "C++":
                    case "PHP":
                    case "Java":
                        foldingStrategy_tbSndMsgData = new BraceFoldingStrategy();
                        break;
                    default:
                        foldingStrategy_tbSndMsgData = null;
                        break;
                }
            }
            if (foldingStrategy_tbSndMsgData != null)
            {
                if (foldingManager_tbSndMsgData == null)
                {
                    foldingManager_tbSndMsgData = FoldingManager.Install(tbSndMsgData.TextArea);
                }
                foldingStrategy_tbSndMsgData.UpdateFoldings(foldingManager_tbSndMsgData, tbSndMsgData.Document);
            }
            else
            {
                if (foldingManager_tbSndMsgData != null)
                {
                    FoldingManager.Uninstall(foldingManager_tbSndMsgData);
                    foldingManager_tbSndMsgData = null;
                }
            }
        }

        private void tbRecvMsgDataHighlightCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tbRecvMsgData.SyntaxHighlighting == null)
            {
                foldingStrategy_tbRecvMsgData = null;
            }
            else
            {
                switch (tbRecvMsgData.SyntaxHighlighting.Name)
                {
                    case "XML":
                        foldingStrategy_tbRecvMsgData = new XmlFoldingStrategy();
                        break;
                    case "C#":
                    case "C++":
                    case "PHP":
                    case "Java":
                        foldingStrategy_tbRecvMsgData = new BraceFoldingStrategy();
                        break;
                    default:
                        foldingStrategy_tbRecvMsgData = null;
                        break;
                }
            }
            if (foldingStrategy_tbRecvMsgData != null)
            {
                if (foldingManager_tbRecvMsgData == null)
                {
                    foldingManager_tbRecvMsgData = FoldingManager.Install(tbRecvMsgData.TextArea);
                }

                foldingStrategy_tbRecvMsgData.UpdateFoldings(foldingManager_tbRecvMsgData, tbRecvMsgData.Document);
            }
            else
            {
                if (foldingManager_tbRecvMsgData != null)
                {
                    FoldingManager.Uninstall(foldingManager_tbRecvMsgData);
                    foldingManager_tbRecvMsgData = null;
                }
            }
        }

        private void tbSndReMsgDataHighlightCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tbSndReMsgData.SyntaxHighlighting == null)
            {
                foldingStrategy_tbSndReMsgData = null;
            }
            else
            {
                switch (tbSndReMsgData.SyntaxHighlighting.Name)
                {
                    case "XML":
                        foldingStrategy_tbSndReMsgData = new XmlFoldingStrategy();
                        break;
                    case "C#":
                    case "C++":
                    case "PHP":
                    case "Java":
                        foldingStrategy_tbSndReMsgData = new BraceFoldingStrategy();
                        break;
                    default:
                        foldingStrategy_tbSndReMsgData = null;
                        break;
                }
            }
            if (foldingStrategy_tbSndReMsgData != null)
            {
                if (foldingManager_tbSndReMsgData == null)
                {
                    foldingManager_tbSndReMsgData = FoldingManager.Install(tbSndReMsgData.TextArea);
                }

                foldingStrategy_tbSndReMsgData.UpdateFoldings(foldingManager_tbSndReMsgData, tbSndReMsgData.Document);
            }
            else
            {
                if (foldingManager_tbSndReMsgData != null)
                {
                    FoldingManager.Uninstall(foldingManager_tbSndReMsgData);
                    foldingManager_tbSndReMsgData = null;
                }
            }
        }
        #endregion

        private void cbAll_ShowLine_Click(object sender, RoutedEventArgs e)
        {
            CheckBox cbAll = sender as CheckBox;
            bool bCheckAll = cbAll.IsChecked == true;

            foreach (DevItemView devItem in lvDevList.Children)
            {
                if (devItem != null)
                {
                    devItem.check.IsChecked = bCheckAll;

                    string strIP = devItem.ip.Text.ToString();

                    ShowLineGraphByIp(strIP, devItem.check.IsChecked == true);
                }
            }

            foreach (DevItemView devItem in lvDevList1.Children)
            {
                if (devItem != null)
                {
                    devItem.check.IsChecked = bCheckAll;

                    string strIP = devItem.ip.Text.ToString();

                    ShowLineGraphByIp(strIP, devItem.check.IsChecked == true);
                }
            }

            foreach (DevItemView devItem in lvDevList2.Children)
            {
                if (devItem != null)
                {
                    devItem.check.IsChecked = bCheckAll;

                    string strIP = devItem.ip.Text.ToString();

                    ShowLineGraphByIp(strIP, devItem.check.IsChecked == true);
                }
            }

            foreach (DevItemView devItem in lvDevList3.Children)
            {
                if (devItem != null)
                {
                    devItem.check.IsChecked = bCheckAll;

                    string strIP = devItem.ip.Text.ToString();

                    ShowLineGraphByIp(strIP, devItem.check.IsChecked == true);
                }
            }

            foreach (DevItemView devItem in lvDevList4.Children)
            {
                if (devItem != null)
                {
                    devItem.check.IsChecked = bCheckAll;

                    string strIP = devItem.ip.Text.ToString();

                    ShowLineGraphByIp(strIP, devItem.check.IsChecked == true);
                }
            }

            bAutoFitToView = true;
        }

        private void onlineCheck_Click(object sender, RoutedEventArgs e)
        {
            if (lvDevList == null || lvDevList1 == null || lvDevList2 == null || lvDevList3 == null || lvDevList4 == null)
            {
                return;
            }

            //判断当前选中那个
            string strCheck = ((RadioButton)sender).Content.ToString();
            if (strCheck == "全部")
            {
                foreach (DevItemView devItem in lvDevList.Children)
                {
                    devItem.Visibility = System.Windows.Visibility.Visible;
                }
                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    devItem.Visibility = System.Windows.Visibility.Visible;
                }
                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    devItem.Visibility = System.Windows.Visibility.Visible;
                }
                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    devItem.Visibility = System.Windows.Visibility.Visible;
                }
                foreach (DevItemView devItem in lvDevList4.Children)
                {
                    devItem.Visibility = System.Windows.Visibility.Visible;
                }
            }
            else if (strCheck == "在线")
            {
                foreach (DevItemView devItem in lvDevList.Children)
                {
                    if (devItem.online.Text == "online")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    if (devItem.online.Text == "online")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    if (devItem.online.Text == "online")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    if (devItem.online.Text == "online")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                foreach (DevItemView devItem in lvDevList4.Children)
                {
                    if (devItem.online.Text == "online")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
            }
            else if (strCheck == "离线")
            {
                foreach (DevItemView devItem in lvDevList.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
                foreach (DevItemView devItem in lvDevList4.Children)
                {
                    if (devItem.online.Text == "offline")
                    {
                        devItem.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        devItem.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
            }
            else
            {

            }
        }

        private List<CreateGPRSInfo.Alias2Gprs> alias2GprsList = null;
        private void ButCreateGPRSInfo_Click(object sender, RoutedEventArgs e)
        {
            CreateGPRSInfo gprsInfo = new CreateGPRSInfo();
            gprsInfo.ShowDialog();

            alias2GprsList = new List<CreateGPRSInfo.Alias2Gprs>();
            foreach (CreateGPRSInfo.Alias2Gprs ag in gprsInfo.alias2GprsList)
            {
                CreateGPRSInfo.Alias2Gprs alias2Gprs = new CreateGPRSInfo.Alias2Gprs();
                alias2Gprs.strAliasName = ag.strAliasName;
                alias2Gprs.ptGprs = ag.ptGprs;

                alias2GprsList.Add(alias2Gprs);
            }

            //更新GPRS信息
            UpdateGprsSetInfo();
        }

        private void ButLoadGPRSInfo_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
            openFileDialog.Title = "选择GPES信息文件";
            openFileDialog.Filter = "excel文件|*.xls|所有文件|*.*";
            openFileDialog.FileName = string.Empty;
            openFileDialog.FilterIndex = 1;
            openFileDialog.RestoreDirectory = true;
            openFileDialog.DefaultExt = "zip";
            System.Windows.Forms.DialogResult result = openFileDialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            //ReadExcel
            DataTable dataTable_rsrp = new DataTable("别名和经纬度信息表");
            dataTable_rsrp.Columns.Add(new DataColumn("序号", typeof(string)));
            dataTable_rsrp.Columns.Add(new DataColumn("别名", typeof(string)));
            dataTable_rsrp.Columns.Add(new DataColumn("经度", typeof(string)));
            dataTable_rsrp.Columns.Add(new DataColumn("纬度", typeof(string)));

            GlobalFun.ReadExcel(dataTable_rsrp, openFileDialog.FileName);

            alias2GprsList = new List<CreateGPRSInfo.Alias2Gprs>();

            for (int i = 0; i < dataTable_rsrp.Rows.Count; i++)
            {
                CreateGPRSInfo.Alias2Gprs alias2Gprs = new CreateGPRSInfo.Alias2Gprs();
                DataRow dataRow = dataTable_rsrp.Rows[i];
                alias2Gprs.strAliasName = dataRow[1].ToString();
                alias2Gprs.ptGprs.X = Double.Parse(dataRow[2].ToString());
                alias2Gprs.ptGprs.Y = Double.Parse(dataRow[3].ToString());

                alias2GprsList.Add(alias2Gprs);
            }

            //更新GPRS信息
            UpdateGprsSetInfo();
        }

        private void ButWriteGPRSInfo_Click(object sender, RoutedEventArgs e)
        {
            //遍历打勾的设备，发送O命令
            foreach (DevItemView devItem in lvDevList.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoWriteGPRSInfo(devItem);
                }
            }
            foreach (DevItemView devItem in lvDevList1.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoWriteGPRSInfo(devItem);
                }
            }
            foreach (DevItemView devItem in lvDevList2.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoWriteGPRSInfo(devItem);
                }
            }
            foreach (DevItemView devItem in lvDevList3.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoWriteGPRSInfo(devItem);
                }
            }
            foreach (DevItemView devItem in lvDevList4.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoWriteGPRSInfo(devItem);
                }
            }
        }

        private void ButClearDevInfo_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定要清空当前设备列表信息吗？\r\n界面清空后，记录仍保留，导出excel信息时仍可导出。", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                //清空
                lvDevList.Children.Clear();
                lvDevList1.Children.Clear();
                lvDevList2.Children.Clear();
                lvDevList3.Children.Clear();
                lvDevList4.Children.Clear();

                lvDevList.Tag = null;
                lvDevList1.Tag = null;
                lvDevList2.Tag = null;
                lvDevList3.Tag = null;
                lvDevList4.Tag = null;
            }
        }

        private void ButReadVer_Click(object sender, RoutedEventArgs e)
        {
            //2次广播获取设备版本信息
            SendGetDevClasSkuFWVInfoCmd(IntPtr.Zero);
            SendGetDevClasSkuFWVInfoCmd(IntPtr.Zero);
        }

        private void ButRssiCheck_Click(object sender, RoutedEventArgs e)
        {
            string strRssi = "{\"reqId\": 40,\"op\": \"R\",\"prop\": [\"apInfo\"]}";
            SendMsgNeedJSonBody(strRssi, IntPtr.Zero);
            SendMsgNeedJSonBody(strRssi, IntPtr.Zero);

            //~
            butRssiSort.Content = "↑↓";
        }

        //信号强度升序还是降序 true 升序 
        bool bUpDown = false;
        private void ButRssiUpDown_Click(object sender, RoutedEventArgs e)
        {
            //点击后对信号强度进行排序
            //Button butRssiUpDoen = sender as Button;
            //if(butRssiUpDoen != null)
            {
                //↑↓
                if (bUpDown)
                {
                    butRssiSort.Content = "↑";
                    SortDevItemListByRssi(true);
                }
                else
                {
                    butRssiSort.Content = "↓";
                    SortDevItemListByRssi(false);
                }


                bUpDown = !bUpDown;
            }
        }

        //信号强度升序还是降序 true 升序 
        private void SortDevItemListByRssi(bool bUpDown = false)
        {
            DoSoetDevItemByRssi(lvDevList);
            DoSoetDevItemByRssi(lvDevList1);
            DoSoetDevItemByRssi(lvDevList2);
            DoSoetDevItemByRssi(lvDevList3);
            DoSoetDevItemByRssi(lvDevList4);
        }

        private bool bDoCheckOnline = false;
        private UInt64 ulCheckOnlineTimes = 0;
        private void ButOnLineCheck_Click(object sender, RoutedEventArgs e)
        {
            //5、	在线检测按钮按下去后，先2次广播{  "wifiInfo", "nbBase",”fwv”,”loc”}，对于回复的认为在线，不回的再单播询问3次{"wifiInfo"}，不回的认为离线。

            bDoCheckOnline = true;
            ulCheckOnlineTimes = ulSystemTickTimes;

            //先设备设备全部离线
            devIP.Items.Clear();

            ComboBoxItem itemIP = new ComboBoxItem();
            itemIP.Content = "0.0.0.0（广播）";
            itemIP.Tag = IntPtr.Zero;
            devIP.Items.Add(itemIP);

            devIP.SelectedIndex = 0;

            //设备列表
            foreach (DevItemView devItem in lvDevList.Children)
            {
                devItem.online.Text = "offline";
            }
            foreach (DevItemView devItem in lvDevList1.Children)
            {
                devItem.online.Text = "offline";
            }
            foreach (DevItemView devItem in lvDevList2.Children)
            {
                devItem.online.Text = "offline";
            }
            foreach (DevItemView devItem in lvDevList3.Children)
            {
                devItem.online.Text = "offline";
            }
            foreach (DevItemView devItem in lvDevList4.Children)
            {
                devItem.online.Text = "offline";
            }

            //2次广播获取设备信息
            SendGetDevInfo_Clas_SkuCmd(IntPtr.Zero);
            SendGetDevInfo_Clas_SkuCmd(IntPtr.Zero);
        }

        private void ButImportDevInfo_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openDlg = new Microsoft.Win32.OpenFileDialog();
            openDlg.DefaultExt = ".xls";
            openDlg.Filter = "Excel文档|*.xls|所有文件|*.*";
            if (openDlg.ShowDialog() == true)
            {
                string strFilePath = openDlg.FileName;
                //MessageBox.Show(strFilePath);
                //GlobalFun.ReadExcel(dataTableDev, strFilePath);
            }
        }

        private void ButExportDevInfo_Click(object sender, RoutedEventArgs e)
        {
            if (dataTableDev != null)
            {
                //清空意味着先期的记录会丢失
                //dataTableDev.Clear();
                //构建列表
                foreach (DevItemView devItem in lvDevList.Children)
                {
                    dataTableDev.Rows.Add(devItem.index.Text, devItem.imei.Text, devItem.aliasName.Text, devItem.tb_Read_JingDu.Text, devItem.tb_Read_WeiDu.Text, "00-00-00-00-00-00 " + devItem.mac.Text, "", "", devItem.ver.Text);
                }
                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    dataTableDev.Rows.Add(devItem.index.Text, devItem.imei.Text, devItem.aliasName.Text, devItem.tb_Read_JingDu.Text, devItem.tb_Read_WeiDu.Text, "00-00-00-00-00-00 " + devItem.mac.Text, "", "", devItem.ver.Text);
                }
                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    dataTableDev.Rows.Add(devItem.index.Text, devItem.imei.Text, devItem.aliasName.Text, devItem.tb_Read_JingDu.Text, devItem.tb_Read_WeiDu.Text, "00-00-00-00-00-00 " + devItem.mac.Text, "", "", devItem.ver.Text);
                }
                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    dataTableDev.Rows.Add(devItem.index.Text, devItem.imei.Text, devItem.aliasName.Text, devItem.tb_Read_JingDu.Text, devItem.tb_Read_WeiDu.Text, "00-00-00-00-00-00 " + devItem.mac.Text, "", "", devItem.ver.Text);
                }
                foreach (DevItemView devItem in lvDevList4.Children)
                {
                    dataTableDev.Rows.Add(devItem.index.Text, devItem.imei.Text, devItem.aliasName.Text, devItem.tb_Read_JingDu.Text, devItem.tb_Read_WeiDu.Text, "00-00-00-00-00-00 " + devItem.mac.Text, "", "", devItem.ver.Text);
                }

                System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();
                saveDlg.InitialDirectory = @"C:\";
                //设置保存的文件的类型，注意过滤器的语法
                saveDlg.Filter = "Excel文档|*.xls|所有文件|*.*";
                saveDlg.FileName = string.Format("{0:yyyy-MM-dd_HH-mm-ss}", System.DateTime.Now) + "_NB_DevList.xls";// 结果为：2010-6-19 20:30

                //调用ShowDialog()方法显示该对话框，该方法的返回值代表用户是否点击了确定按钮
                if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    //MessageBox.Show("保存成功");
                    string strFilePath = saveDlg.FileName;// System.Windows.Forms.Application.StartupPath + "\\DevList.xls";
                    if (File.Exists(strFilePath) == true)
                    {
                        //文件存在
                        File.Delete(strFilePath);
                    }

                    GlobalFun.WriteExcel(dataTableDev, strFilePath);
                    //dataTableDev.Clear();
                }
                else
                {
                    //MessageBox.Show("取消保存");
                }
            }
        }

        private void cbAll_OTA_Click(object sender, RoutedEventArgs e)
        {
            CheckBox cbAllOTA = sender as CheckBox;
            bool bCheckAll = cbAllOTA.IsChecked == true;

            foreach (DevItemView devItem in lvDevList.Children)
            {
                if (devItem != null)
                {
                    devItem.checkOTA.IsChecked = bCheckAll;
                }
            }
            foreach (DevItemView devItem in lvDevList1.Children)
            {
                if (devItem != null)
                {
                    devItem.checkOTA.IsChecked = bCheckAll;
                }
            }
            foreach (DevItemView devItem in lvDevList2.Children)
            {
                if (devItem != null)
                {
                    devItem.checkOTA.IsChecked = bCheckAll;
                }
            }
            foreach (DevItemView devItem in lvDevList3.Children)
            {
                if (devItem != null)
                {
                    devItem.checkOTA.IsChecked = bCheckAll;
                }
            }
            foreach (DevItemView devItem in lvDevList4.Children)
            {
                if (devItem != null)
                {
                    devItem.checkOTA.IsChecked = bCheckAll;
                }
            }
        }

        private void cbShowCurVer_Click(object sender, RoutedEventArgs e)
        {
            UpdateDevItemVisible();
        }

        private bool bAutoSendRssiCmd = false;
        private DateTime dtStartReadRssi = new DateTime();
        private void ButRssi_Click(object sender, RoutedEventArgs e)
        {
            //nbSignal
            //string strScan = "{\"reqId\": 40,\"op\": \"R\",\"prop\": [\"apInfo\"]}";

            //IntPtr intPrt = IntPtr.Zero;
            //ComboBoxItem itemSel = devIP.SelectedItem as ComboBoxItem;
            //if (itemSel != null)
            //{
            //    intPrt = (IntPtr)(itemSel.Tag);
            //}

            //bool bOK = SendMsgNeedJSonBody(strScan, intPrt);        
            SystemConfig.ConfigItem itemNew = new SystemConfig.ConfigItem();
            itemNew.strName = "SignalReTime";
            itemNew.strValue = tbSignalReTime.Text;
            systemConfig.UpdateConfigItemValue(itemNew);

            //只要此按钮点击过，则tbSignalReTime就置灰，不再允许编辑，且记忆进系统配置文件
            tbSignalReTime.IsEnabled = false;

            bAutoSendRssiCmd = !bAutoSendRssiCmd;
            if (bAutoSendRssiCmd)
            {
                butRssi.Content = "停止信号检测";

                string strScan = "{\"reqId\": 40,\"op\": \"R\",\"prop\": [\"nbSignal\"]}";
                //广播方式
                bool bOK = SendMsgNeedJSonBody(strScan, IntPtr.Zero);

                strScan = "{\"reqId\": 40,\"op\": \"R\",\"prop\": [\"apInfo\"]}";
                bOK = SendMsgNeedJSonBody(strScan, IntPtr.Zero);

                UInt16 uiSecond = GlobalFun.StringToUInt16(tbSignalReTime.Text);
                //根据上次时间算出当前点击应该是多少时间了。
                if (dtStartReadRssi.Year == 1 && dtStartReadRssi.Month == 1)
                {
                    dtStartReadRssi = DateTime.Now;
                }
                else
                {
                    double dPassSec = (DateTime.Now - dtStartReadRssi).Seconds;
                    dChartTimes += (dPassSec / uiSecond);
                }

                //开启Chart定时器
                chartTimer = new DispatcherTimer();
                chartTimer.Interval = TimeSpan.FromSeconds(uiSecond);
                chartTimer.Tag = uiSecond;
                chartTimer.Tick += chartTimer_Tick;
                chartTimer.Start();

                //更新X轴显示含义
                string strXTitle = "时间( * " + tbSignalReTime.Text + "S )";
                horAxisTitle_rsrp.Content = strXTitle;
                horAxisTitle_txpower.Content = strXTitle;
                horAxisTitle_snr.Content = strXTitle;
                horAxisTitle_cellID.Content = strXTitle;
                horAxisTitle_rssi.Content = strXTitle;
            }
            else
            {
                butRssi.Content = "开始信号检测";
                if (chartTimer != null)
                    chartTimer.Stop();
            }
        }

        public class TagTimes
        {
            public string strTag;
            public UInt16 uiTimes;
        }
        private List<TagTimes> tagTimesList = new List<TagTimes>();

        private UInt16 AddTagTimes(string strTag)
        {
            foreach (TagTimes tagTimes in tagTimesList)
            {
                if (tagTimes.strTag == strTag)
                {
                    tagTimes.uiTimes++;
                    return tagTimes.uiTimes;
                }
            }

            //Add New
            TagTimes tag = new TagTimes();
            tag.strTag = strTag;
            tag.uiTimes = 0;
            tagTimesList.Add(tag);

            return tag.uiTimes;
        }

        private void cbShow_GPRS_Click(object sender, RoutedEventArgs e)
        {
            if (cbShowGPRSInfo.IsChecked == true)
            {
                //显示
                spGPRSInfo.Visibility = System.Windows.Visibility.Visible;

                foreach (DevItemView devItem in lvDevList.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Visible;

                    devItem.SetGprsState();
                }
                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Visible;

                    devItem.SetGprsState();
                }
                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Visible;

                    devItem.SetGprsState();
                }
                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Visible;

                    devItem.SetGprsState();
                }
                foreach (DevItemView devItem in lvDevList4.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Visible;

                    devItem.SetGprsState();
                }
            }
            else
            {
                //隐藏
                spGPRSInfo.Visibility = System.Windows.Visibility.Collapsed;

                foreach (DevItemView devItem in lvDevList.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Collapsed;
                }
                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Collapsed;
                }
                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Collapsed;
                }
                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Collapsed;
                }
                foreach (DevItemView devItem in lvDevList4.Children)
                {
                    devItem.spGPRSInfo.Visibility = System.Windows.Visibility.Collapsed;
                }
            }

            //更新GPRS信息
            UpdateGprsSetInfo();
        }

        private void ButExternChart_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();
            saveDlg.InitialDirectory = @"C:\";
            //设置保存的文件的类型，注意过滤器的语法
            saveDlg.Filter = "Excel文档|*.xls|所有文件|*.*";
            saveDlg.FileName = string.Format("{0:yyyy-MM-dd_HH-mm-ss}", System.DateTime.Now) + "_PerformanceData.xls";// 结果为：2010-6-19 20:30

            //调用ShowDialog()方法显示该对话框，该方法的返回值代表用户是否点击了确定按钮
            if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //MessageBox.Show("保存成功");
                string strFilePath = saveDlg.FileName;
                File.Delete(strFilePath);
                //GlobalFun.WriteExcel(dataTable_rsrp, strFilePath);

                int nTableIndex = 0;
                tagTimesList.Clear();
                HSSFWorkbook book = null;
                foreach (SignalData data in sdMng.SignalDatas)
                {
                    //"_rsrp"
                    //"_txpower"
                    //"_snr"
                    //"_cellID"

                    string strMac = data.strMac;
                    string strAliasName = data.strAliasName;
                    string strImei = data.strImei;

                    //总时间为最后一个点时间减去第一个点时间
                    int nPtCount = data.mSignalRecord.Collection.Count;
                    string strTotalTime = data.dtStartTime.ToString() + " -- " + data.dtStartTime.AddSeconds(nPtCount * GlobalFun.StringToUInt16(tbSignalReTime.Text)).ToString();

                    //详细数据记录
                    string strTag = data.strIPAndTag.Substring(data.strIPAndTag.IndexOf("_") + 1);
                    DataTable dataTable_rsrp = new DataTable(strTag);
                    dataTable_rsrp.Columns.Add(new DataColumn("序号", typeof(string)));
                    dataTable_rsrp.Columns.Add(new DataColumn("时间", typeof(string)));
                    dataTable_rsrp.Columns.Add(new DataColumn("Value", typeof(string)));

                    //计算插入Excel的位置
                    nTableIndex = AddTagTimes(strTag);

                    //平均值为所有值求取平均数
                    double dTotalSum = 0.0;
                    int nRowIndex = 1;
                    foreach (Point pt in data.mSignalRecord.Collection)
                    {
                        dTotalSum += pt.Y;
                        dataTable_rsrp.Rows.Add((nRowIndex).ToString(), data.dtStartTime.AddSeconds(GlobalFun.StringToUInt16(tbSignalReTime.Text) * nRowIndex).ToString(), pt.Y.ToString());
                        nRowIndex++;
                    }
                    string strAverageValue = (dTotalSum / nPtCount).ToString();

                    book = GlobalFun.WriteExcelExtern(book, strMac, strAliasName, strImei, strTotalTime, strAverageValue, dataTable_rsrp, nTableIndex, strFilePath);
                    nTableIndex += 4;
                }
            }
            else
            {
                //MessageBox.Show("取消保存");
            }
        }

        private void ButSendMsg_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            IntPtr intPrt = IntPtr.Zero;
            ComboBoxItem itemSel = devIP.SelectedItem as ComboBoxItem;
            if (itemSel != null)
            {
                //intPrt = (IntPtr)(itemSel.Tag);
                intPrt = macAndIDManager.GetIDByMac(itemSel.Tag.ToString());
            }

            bool bOK = SendMsgNeedJSonBody(tbSndMsgData.Text, intPrt, cbContentType.Text);

            if (cbReEnable.IsChecked == true && reTimesTimer == null)
            {
                //获取重发次数和间隔时间
                UInt16 uiReTimes = GlobalFun.StringToUInt16(tbReTimes.Text);
                UInt16 uiReTime = GlobalFun.StringToUInt16(tbReTime.Text);

                butSend.IsEnabled = false;

                uiSendMsgTimes = uiReTimes;
                lbTimes.Content = uiSendMsgTimes.ToString() + " / " + tbReTimes.Text;

                if (reTimesTimer != null)
                {
                    reTimesTimer.Stop();
                }
                reTimesTimer = new DispatcherTimer();
                reTimesTimer.Interval = TimeSpan.FromMilliseconds(uiReTime);
                reTimesTimer.Tick += reTimesTimer_Tick;
                reTimesTimer.Start();
            }
        }

        private void ButScan_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SendGetDevInfo_Clas_SkuCmd(IntPtr.Zero);
        }

        private void ButSetIP_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            NetLink.GetNetLink().UnInitNetLink();
            NetLink.GetNetLink().InitNetLink(srcIP.Text);
            hfsIP.Text = srcIP.Text;
            if (MessageBox.Show("绑定成功，是否开始扫描设备？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                SendGetDevInfo_Clas_SkuCmd(IntPtr.Zero);
            }
        }

        //private UInt16 uiOTATimes = 0;
        //private bool bAutoSendScanCmd = false;
        private void ButDoOTA_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定要对选中的设备进行OTA？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
            {
                return;
            }

            string strIP = hfsIP.Text;// "192.168.10.99";
            if (GlobalFun.IsRightIP(strIP) == false)
            {
                MessageBox.Show("hfs IP 信息无效！");
                return;
            }
            string strPort = hfsPort.Text;//80
            string strBinFile = tbOTABinFile.Text;

            //记忆
            iniFile.WriteValue("OTAConfig", "OTA_IP", strIP);
            iniFile.WriteValue("OTAConfig", "OTA_Port", strPort);
            iniFile.WriteValue("OTAConfig", "OTA_BinFile", strBinFile);
            iniFile.WriteValue("OTAConfig", "OTA_Ver", tbOTABinFileVer.Text);

            //遍历打勾的设备，发送OTA命令
            int nOTASize = 0;
            int nVerIsOKSize = 0;
            foreach (DevItemView devItem in lvDevList.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoBeginOTA(devItem);

                    IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                    //bool bOK = SendOTACmd(strIP, strPort, strBinFile, intPtr);
                    //SendOTACmd_Ex
                    bool bOK = SendOTACmd_Ex(strIP, strPort, strBinFile, intPtr);
                    if(bOK == false)
                    {
                        MessageBox.Show("Bin文件 " + strBinFile + " 有问题，请检查！");
                        break;
                    }

                    nOTASize++;
                }
                else
                {
                    if (devItem.ver.Text == tbOTABinFileVer.Text)
                    {
                        nVerIsOKSize++;
                    }
                }
            }

            foreach (DevItemView devItem in lvDevList1.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoBeginOTA(devItem);

                    IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                    //bool bOK = SendOTACmd(strIP, strPort, strBinFile, intPtr);
                    //SendOTACmd_Ex
                    bool bOK = SendOTACmd_Ex(strIP, strPort, strBinFile, intPtr);
                    if (bOK == false)
                    {
                        MessageBox.Show("Bin文件 " + strBinFile + " 有问题，请检查！");
                        break;
                    }

                    nOTASize++;
                }
                else
                {
                    if (devItem.ver.Text == tbOTABinFileVer.Text)
                    {
                        nVerIsOKSize++;
                    }
                }
            }

            foreach (DevItemView devItem in lvDevList2.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoBeginOTA(devItem);

                    IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                    //bool bOK = SendOTACmd(strIP, strPort, strBinFile, intPtr);
                    //SendOTACmd_Ex
                    bool bOK = SendOTACmd_Ex(strIP, strPort, strBinFile, intPtr);
                    if (bOK == false)
                    {
                        MessageBox.Show("Bin文件 " + strBinFile + " 有问题，请检查！");
                        break;
                    }

                    nOTASize++;
                }
                else
                {
                    if (devItem.ver.Text == tbOTABinFileVer.Text)
                    {
                        nVerIsOKSize++;
                    }
                }
            }

            foreach (DevItemView devItem in lvDevList3.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoBeginOTA(devItem);

                    IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                    //bool bOK = SendOTACmd(strIP, strPort, strBinFile, intPtr);
                    //SendOTACmd_Ex
                    bool bOK = SendOTACmd_Ex(strIP, strPort, strBinFile, intPtr);
                    if (bOK == false)
                    {
                        MessageBox.Show("Bin文件 " + strBinFile + " 有问题，请检查！");
                        break;
                    }

                    nOTASize++;
                }
                else
                {
                    if (devItem.ver.Text == tbOTABinFileVer.Text)
                    {
                        nVerIsOKSize++;
                    }
                }
            }

            foreach (DevItemView devItem in lvDevList4.Children)
            {
                if (devItem.checkOTA.IsChecked == true)
                {
                    DoBeginOTA(devItem);

                    IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                    //bool bOK = SendOTACmd(strIP, strPort, strBinFile, intPtr);
                    //SendOTACmd_Ex
                    bool bOK = SendOTACmd_Ex(strIP, strPort, strBinFile, intPtr);
                    if (bOK == false)
                    {
                        MessageBox.Show("Bin文件 " + strBinFile + " 有问题，请检查！");
                        break;
                    }

                    nOTASize++;
                }
                else
                {
                    if (devItem.ver.Text == tbOTABinFileVer.Text)
                    {
                        nVerIsOKSize++;
                    }
                }
            }

            //记录版本一致的数量
            lbOTASuccessedInfo.Tag = (nOTASize + nVerIsOKSize).ToString();

            //清空
            //lvDevList.Children.Clear();

            //uiOTATimes = 0;
            //bAutoSendScanCmd = true;

            //系统全局定时器查询，与设定的版本号比对，一致的认为升级成功。

            //启动升级状态判断
            return;
        }

        private void ButClearOTA_Click(object sender, RoutedEventArgs e)
        {
            //foreach (DevItemView devItem in lvDevList.Children)
            //{
            //    devItem.pbOTAing.Visibility = System.Windows.Visibility.Collapsed;
            //}
        }

        private void ButVerCheck_Click(object sender, RoutedEventArgs e)
        {
            bool bOK = SendRequreVerCmd(IntPtr.Zero);
        }

        DataTable dataTable_QuickCmd = new DataTable("快捷命令发送接收统计");
        private void ButExternCountQuickCmd_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();
            saveDlg.InitialDirectory = @"C:\";
            //设置保存的文件的类型，注意过滤器的语法
            saveDlg.Filter = "Excel文档|*.xls|所有文件|*.*";
            saveDlg.FileName = string.Format("{0:yyyy-MM-dd_HH-mm-ss}", System.DateTime.Now) + "_QuickCmdData.xls";// 结果为：2010-6-19 20:30

            //调用ShowDialog()方法显示该对话框，该方法的返回值代表用户是否点击了确定按钮
            if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //MessageBox.Show("保存成功");
                string strFilePath = saveDlg.FileName;
                File.Delete(strFilePath);
                GlobalFun.WriteExcelExtern1(dataTable_QuickCmd, strFilePath);
            }
            else
            {
                //MessageBox.Show("取消保存");
            }
        }

        private void ButAddQuickCmd_Click(object sender, RoutedEventArgs e)
        {
            string strCmdName = tbCmdName.Text;
            if (strCmdName.Length <= 0)
            {
                MessageBox.Show("名字不可为空，请确认！");
                return;
            }
            else
            {
                //判断当前是否已存在，若存在提醒
                SendCmds.SendCmd sendCmd = sendCmds.FindSendCmdByName(strCmdName);
                if (sendCmd != null)
                {
                    MessageBoxResult msgBoxRet = MessageBox.Show("当前已存在 [" + strCmdName + "] 的编辑快捷命令，是否覆盖？", "确认", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                    if (msgBoxRet == MessageBoxResult.Yes)
                    {
                        //覆盖，更新内存，删除再添加
                        bool bOK = sendCmds.RemoveCmd(strCmdName);
                        if(bOK == false)
                            MessageBox.Show("系统找不到 " + strCmdName + " 的内存信息！");

                        sendCmd = new SendCmds.SendCmd();
                        sendCmd.strName = strCmdName;
                        sendCmd.strProl_ID = tbProlID.Text;
                        sendCmd.strProl_Ver = tbProlVer.Text;
                        sendCmd.strIsRsp = tbIsRsp.Text;
                        sendCmd.strContentType = cbContentType.Text;
                        sendCmd.strDatas = tbSndMsgData.Text;
                        sendCmds.AddNewCmd(sendCmd);

                        //保存到XML
                        sendCmds.Save();
                    }
                    else
                    {
                        //不覆盖
                        return;
                    }
                }
                else
                {
                    //添加到界面
                    //ButThumb butAdd = new ButThumb();
                    //butAdd.Margin = new Thickness(5);
                    //butAdd.strTitle = strCmdName;
                    //butAdd.Height = 22;
                    ////string col = "#FFD8ECD1";
                    ////this.BackColor = System.Drawing.ColorTranslator.FromHtml(col); 
                    //butAdd.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xD8, 0xEC, 0xD1));
                    //butAdd.Click += butQuickCmd_Click;
                    //butAdd.MouseRightButtonUp += butQuickCmd_RightClick;

                    //cmdCanvas.Children.Add(butAdd);
                    //thumbList.Add(butAdd);

                    //svCmd.ScrollToEnd();

                    //添加到内存
                    sendCmd = new SendCmds.SendCmd();
                    sendCmd.strName = strCmdName;
                    sendCmd.strProl_ID = tbProlID.Text;
                    sendCmd.strProl_Ver = tbProlVer.Text;
                    sendCmd.strIsRsp = tbIsRsp.Text;
                    sendCmd.strContentType = cbContentType.Text;
                    sendCmd.strDatas = tbSndMsgData.Text;
                    sendCmds.AddNewCmd(sendCmd);

                    //界面处理
                    ButThumb butLast = thumbList[thumbList.Count - 1];
                    int nSize = sendCmds.sendCmdArry.Count; ;//.uiSendCmdCount;

                    //cmdCanvas.Width = svCmd.ActualWidth + 10;
                    //cmdCanvas.Height = svCmd.ActualHeight + 50;

                    int mParentWidth = (int)cmdCanvas.Width;
                    int nThumbWidth = 110;
                    int nThumbHeight = 30;
                    int count = mParentWidth / (nThumbWidth + 5);
                    int nTop = 0;
                    int nLeft = 0;
                    int nRow = 0;
                    int nColumn = 0;

                    ButThumb butAdd = null;
                    for (int i = nSize - 1; i < nSize; i++)
                    {
                        nColumn = i % count;
                        nLeft = nColumn * nThumbWidth;
                        nRow = i / count;
                        nTop = nRow * nThumbHeight;

                        butAdd = new ButThumb();
                        //butAdd.Margin = new Thickness(2);
                        butAdd.strTitle = sendCmd.strName;
                        butAdd.Index = zIndex++;
                        butAdd.ParentControl = cmdCanvas;
                        //拖动改变完位置后，这个变量需要更新？？？
                        butAdd.RectangleGeometry = new RectangleGeometry() { Rect = new Rect(5 + nLeft + 3 * nColumn, nTop - 5 * nRow, nThumbWidth, nThumbHeight) };
                        //butAdd.Width = wth;
                        butAdd.Height = nThumbHeight;
                        butAdd.ToolTip = sendCmd.strName;

                        //string col = "#FFD8ECD1";
                        //this.BackColor = System.Drawing.ColorTranslator.FromHtml(col); 
                        butAdd.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xD8, 0xEC, 0xD1));
                        //butAdd.Background = new SolidColorBrush(Colors.LightBlue);
                        //LightBlue
                        //butAdd.MouseDownClick += butQuickCmd_Click;
                        butAdd.MouseRightButtonUp += butQuickCmd_RightClick;

                        Canvas.SetLeft(butAdd, 5 + nLeft + 3 * nColumn);
                        Canvas.SetTop(butAdd, nTop - 5 * nRow);
                        Canvas.SetZIndex(butAdd, butAdd.Index);
                        butAdd.DragDelta += mdThumb_DragDelta;
                        butAdd.MyMouseLeftButtonDown += mdThumb_MyMouseLeftButtonDown;
                        butAdd.MyMouseLeftButtonUp += mdThumb_MyMouseLeftButtonUp;
                        butAdd.MouseDownClick += butQuickCmd_Click;

                        cmdCanvas.Children.Add(butAdd);
                        thumbList.Add(butAdd);
                    }

                    if (butAdd != null)
                    {
                        cmdCanvas.Width = svCmd.ActualWidth + 10;
                        cmdCanvas.Height = Canvas.GetTop(butAdd) + nThumbHeight;
                    }

                    svCmd.ScrollToEnd();
                }
            }
        }

        private void butQuickCmd_Click(object sender, RoutedEventArgs e)
        {
            ButThumb butThumb = sender as ButThumb;

            //Button butCmd = sender as Button;

            //主动设置显示的内容
            Button butCmd = (Button)butThumb.Template.FindName("Button", butThumb);

            if (butCmd != null)
            {
                string strCmdName = butCmd.Content.ToString();

                //根据名称反查命令，然后发送               

                SendCmds.SendCmd sendCmd = sendCmds.FindSendCmdByName(strCmdName);
                string strJson = sendCmd.strDatas;

                //获取当前IP
                string strIP = srcIP.Text;
                strIP = strIP.Substring(strIP.LastIndexOf('.') + 1);
                UInt16 uiIP = GlobalFun.StringToUInt16(strIP);
                //组合成SeqNum
                UInt32 unSeqNum = (UInt32)((uiIP << 16) + _uiSeqNum);

                if (cbQuickCmdBut.IsChecked == true)
                {
                    //广播，忽略设备勾选情况
                    if (cbCountQuickCmd.IsChecked == true)
                    {
                        //添加进统计
                        string strJsonTemp = strJson.Trim(new char[] { '\r', '\n' });
                        strJsonTemp = strJsonTemp.Replace("\r\n", "");
                        DataRow row = dataTable_QuickCmd.Rows.Add((dataTable_QuickCmd.Rows.Count + 1).ToString(), "广播", "广播", DateTime.Now.ToString(), strJsonTemp, "", "");

                        int nIndex = 0;
                        byte[] byArry = new byte[4];
                        GlobalFun.BasicTypeToByteArrayEndian(unSeqNum, byArry, nIndex, out nIndex);

                        row.RowError = GlobalFun.ByteArrayToHexString(byArry, byArry.Length, " ");
                        row.RowError = row.RowError.Trim();
                    }

                    IntPtr intPtr = IntPtr.Zero;
                    bool bOK = SendMsgNeedJSonBody(strJson, intPtr, sendCmd.strContentType);
                }
                else
                {
                    //遍历打勾的设备，发送O命令
                    foreach (DevItemView devItem in lvDevList.Children)
                    {
                        if (devItem.checkOTA.IsChecked == true)
                        {
                            if (cbCountQuickCmd.IsChecked == true)
                            {
                                //添加进统计
                                string strJsonTemp = strJson.Trim(new char[] { '\r', '\n' });
                                strJsonTemp = strJsonTemp.Replace("\r\n", "");
                                DataRow row = dataTable_QuickCmd.Rows.Add((dataTable_QuickCmd.Rows.Count + 1).ToString(), devItem.mac.Text, devItem.imei.Text, DateTime.Now.ToString(), strJsonTemp, "", "");

                                int nIndex = 0;
                                byte[] byArry = new byte[4];
                                GlobalFun.BasicTypeToByteArrayEndian(unSeqNum, byArry, nIndex, out nIndex);

                                row.RowError = GlobalFun.ByteArrayToHexString(byArry, byArry.Length, " ");
                                row.RowError = row.RowError.Trim();
                            }

                            IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                            bool bOK = SendMsgNeedJSonBody(strJson, intPtr, sendCmd.strContentType);
                        }
                    }

                    foreach (DevItemView devItem in lvDevList1.Children)
                    {
                        if (devItem.checkOTA.IsChecked == true)
                        {
                            if (cbCountQuickCmd.IsChecked == true)
                            {
                                //添加进统计
                                string strJsonTemp = strJson.Trim(new char[] { '\r', '\n' });
                                strJsonTemp = strJsonTemp.Replace("\r\n", "");
                                DataRow row = dataTable_QuickCmd.Rows.Add((dataTable_QuickCmd.Rows.Count + 1).ToString(), devItem.mac.Text, devItem.imei.Text, DateTime.Now.ToString(), strJsonTemp, "", "");

                                int nIndex = 0;
                                byte[] byArry = new byte[4];
                                GlobalFun.BasicTypeToByteArrayEndian(unSeqNum, byArry, nIndex, out nIndex);

                                row.RowError = GlobalFun.ByteArrayToHexString(byArry, byArry.Length, " ");
                                row.RowError = row.RowError.Trim();
                            }

                            IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                            bool bOK = SendMsgNeedJSonBody(strJson, intPtr, sendCmd.strContentType);
                        }
                    }

                    foreach (DevItemView devItem in lvDevList2.Children)
                    {
                        if (devItem.checkOTA.IsChecked == true)
                        {
                            if (cbCountQuickCmd.IsChecked == true)
                            {
                                //添加进统计
                                string strJsonTemp = strJson.Trim(new char[] { '\r', '\n' });
                                strJsonTemp = strJsonTemp.Replace("\r\n", "");
                                DataRow row = dataTable_QuickCmd.Rows.Add((dataTable_QuickCmd.Rows.Count + 1).ToString(), devItem.mac.Text, devItem.imei.Text, DateTime.Now.ToString(), strJsonTemp, "", "");

                                int nIndex = 0;
                                byte[] byArry = new byte[4];
                                GlobalFun.BasicTypeToByteArrayEndian(unSeqNum, byArry, nIndex, out nIndex);

                                row.RowError = GlobalFun.ByteArrayToHexString(byArry, byArry.Length, " ");
                                row.RowError = row.RowError.Trim();
                            }

                            IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                            bool bOK = SendMsgNeedJSonBody(strJson, intPtr, sendCmd.strContentType);
                        }
                    }

                    foreach (DevItemView devItem in lvDevList3.Children)
                    {
                        if (devItem.checkOTA.IsChecked == true)
                        {
                            if (cbCountQuickCmd.IsChecked == true)
                            {
                                //添加进统计
                                string strJsonTemp = strJson.Trim(new char[] { '\r', '\n' });
                                strJsonTemp = strJsonTemp.Replace("\r\n", "");
                                DataRow row = dataTable_QuickCmd.Rows.Add((dataTable_QuickCmd.Rows.Count + 1).ToString(), devItem.mac.Text, devItem.imei.Text, DateTime.Now.ToString(), strJsonTemp, "", "");

                                int nIndex = 0;
                                byte[] byArry = new byte[4];
                                GlobalFun.BasicTypeToByteArrayEndian(unSeqNum, byArry, nIndex, out nIndex);

                                row.RowError = GlobalFun.ByteArrayToHexString(byArry, byArry.Length, " ");
                                row.RowError = row.RowError.Trim();
                            }

                            IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                            bool bOK = SendMsgNeedJSonBody(strJson, intPtr, sendCmd.strContentType);
                        }
                    }

                    foreach (DevItemView devItem in lvDevList4.Children)
                    {
                        if (devItem.checkOTA.IsChecked == true)
                        {
                            if (cbCountQuickCmd.IsChecked == true)
                            {
                                //添加进统计
                                string strJsonTemp = strJson.Trim(new char[] { '\r', '\n' });
                                strJsonTemp = strJsonTemp.Replace("\r\n", "");
                                DataRow row = dataTable_QuickCmd.Rows.Add((dataTable_QuickCmd.Rows.Count + 1).ToString(), devItem.mac.Text, devItem.imei.Text, DateTime.Now.ToString(), strJsonTemp, "", "");

                                int nIndex = 0;
                                byte[] byArry = new byte[4];
                                GlobalFun.BasicTypeToByteArrayEndian(unSeqNum, byArry, nIndex, out nIndex);

                                row.RowError = GlobalFun.ByteArrayToHexString(byArry, byArry.Length, " ");
                                row.RowError = row.RowError.Trim();
                            }

                            IntPtr intPtr = (IntPtr)(devItem.Tag);// as IntPtr;
                            bool bOK = SendMsgNeedJSonBody(strJson, intPtr, sendCmd.strContentType);
                        }
                    }
                }
            }
        }

        private void butQuickCmd_RightClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ButThumb butThumb = sender as ButThumb;
            //主动设置显示的内容
            Button butCmd = (Button)butThumb.Template.FindName("Button", butThumb);

            string strButName = "";
            //Button but = sender as Button;
            if (butCmd != null)
            {
                strButName = butCmd.Content.ToString();
            }

            MessageBoxResult msgBoxRet = MessageBox.Show("确定要对 [" + strButName + "] 执行以下操作吗？\r\n点击[Yes]将删除快捷命令\r\n点击[No]将编辑快捷命令", "确认", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
            if (msgBoxRet == MessageBoxResult.Yes)
            {
                //删除
                cmdCanvas.Children.Remove(butThumb);
                thumbList.Remove(butThumb);
                sendCmds.RemoveCmd(strButName);
            }
            else if (msgBoxRet == MessageBoxResult.No)
            {
                //编辑
                //将内容更新到命令编辑区域，然后再次添加到快捷命令列表
                SendCmds.SendCmd sendCmd = sendCmds.FindSendCmdByName(strButName);

                tbProlID.Text = sendCmd.strProl_ID;
                tbProlVer.Text = sendCmd.strProl_Ver;
                tbIsRsp.Text = sendCmd.strIsRsp;
                cbContentType.Text = sendCmd.strContentType;

                tbSndMsgData.Text = sendCmd.strDatas;

                tbCmdName.Text = strButName;
            }
            else
            {
                //Cancel
            }
        }

        public bool bAutoFitToView = false;
        private void signlRecord_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //e.Handled = true;

            ChartPlotter chart = sender as ChartPlotter;
            if (chart != null)
            {
                if (gridChart.RowDefinitions[0].Height == new GridLength(0, GridUnitType.Pixel) || gridChart.RowDefinitions[1].Height == new GridLength(0, GridUnitType.Pixel))
                {
                    //需要恢复
                    gridChart.RowDefinitions[0].Height = new GridLength(50, GridUnitType.Star);
                    gridChart.RowDefinitions[1].Height = new GridLength(50, GridUnitType.Star);

                    gridChart.ColumnDefinitions[0].Width = new GridLength(50, GridUnitType.Star);
                    gridChart.ColumnDefinitions[1].Width = new GridLength(50, GridUnitType.Star);
                }
                else
                {
                    if (chart == signlRecord_rsrp)
                    {
                        gridChart.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Pixel);
                        gridChart.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
                    }
                    else if (chart == signlRecord_txpower)
                    {
                        gridChart.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Pixel);
                        gridChart.ColumnDefinitions[0].Width = new GridLength(0, GridUnitType.Pixel);
                    }
                    else if (chart == signlRecord_snr)
                    {
                        gridChart.RowDefinitions[0].Height = new GridLength(0, GridUnitType.Pixel);
                        gridChart.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
                    }
                    else if (chart == signlRecord_cellID)
                    {
                        gridChart.RowDefinitions[0].Height = new GridLength(0, GridUnitType.Pixel);
                        gridChart.ColumnDefinitions[0].Width = new GridLength(0, GridUnitType.Pixel);
                    }
                }
                gridChart.UpdateLayout();

                chart.Viewport.AutoFitToView = true;
                chart.Viewport.FitToView();

                e.Handled = true;

                bAutoFitToView = true;
            }
        }

        private void tbRecvMsgData_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            e.Handled = true;

            try
            {
                string strSelect = tbRecvMsgData.SelectedText.ToString();

                //从当前位置到头，截取字符串
                string strText = tbRecvMsgData.Text.Substring(0, tbRecvMsgData.SelectionStart);
                //从后往前找，第一个出//的数据，截取后面的IP信息
                int nIndex = strText.LastIndexOf(@"//");
                string strIPInfo = strText.Substring(nIndex);
                nIndex = strIPInfo.IndexOf("[");
                int nEndIndex = strIPInfo.IndexOf("]");
                strIPInfo = strIPInfo.Substring(nIndex, nEndIndex - nIndex);
                strIPInfo = strIPInfo.Replace("[", "");
                strIPInfo = strIPInfo.Replace("]", "");

                nIndex = strIPInfo.IndexOf(":");
                strIPInfo = strIPInfo.Substring(0, nIndex);
                strIPInfo = strIPInfo.Replace(" ", "");

                foreach (DevItemView devItem in lvDevList.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);

                    if (devItem.ip.Text == strIPInfo)
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGreen);
                    }
                }
                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);

                    if (devItem.ip.Text == strIPInfo)
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGreen);
                    }
                }
                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);

                    if (devItem.ip.Text == strIPInfo)
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGreen);
                    }
                }
                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);

                    if (devItem.ip.Text == strIPInfo)
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGreen);
                    }
                }
                foreach (DevItemView devItem in lvDevList4.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);

                    if (devItem.ip.Text == strIPInfo)
                    {
                        devItem.Background = new SolidColorBrush(Colors.LightGreen);
                    }
                }
            }
            catch (Exception)
            {
                foreach (DevItemView devItem in lvDevList.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);
                }
                foreach (DevItemView devItem in lvDevList1.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);
                }
                foreach (DevItemView devItem in lvDevList2.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);
                }
                foreach (DevItemView devItem in lvDevList3.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);
                }
                foreach (DevItemView devItem in lvDevList4.Children)
                {
                    devItem.Background = new SolidColorBrush(Colors.Transparent);
                }
            }
        }

        private void listViewLog_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Delete)
            {
                //删除选中的条目

                if (MessageBox.Show("确定要清空Log记录吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    DataPackInfoList.Clear();
                }
            }
        }

        double dBorderCol_0 = -999;
        private void GridSplitter_MouseDoubleClick_Column(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //双击后，自动最大化设备条目栏
            //先记录
            if(dBorderCol_0 == -999)
            {
                //最大化条目栏
                dBorderCol_0 = gridCol_0.ActualWidth;
                gridCol_0.Width = new GridLength(0);
            }
            else
            {
                //复原条目栏
                gridCol_0.Width = new GridLength(dBorderCol_0);
                dBorderCol_0 = -999;
            }
        }

        double dBorderRow_2 = -999;
        private void GridSplitter_MouseDoubleClick_Row(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //双击后，自动最大化设备条目栏
            //先记录
            if (dBorderRow_2 == -999)
            {
                //最大化条目栏
                dBorderRow_2 = gridRow_2.ActualHeight;
                gridRow_2.Height = new GridLength(0);
            }
            else
            {
                //复原条目栏
                gridRow_2.Height = new GridLength(dBorderRow_2);
                dBorderRow_2 = -999;
            }
        }

        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            labelForTabel.Content = ((TabItem) ((TabControl)sender).SelectedItem).Header;

            if(labelForTabel.Content.ToString().Contains("日志"))
            {
                spTabCtrl.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                spTabCtrl.Visibility = System.Windows.Visibility.Visible;
            }

            butExPortChatInfo.Visibility = System.Windows.Visibility.Visible;
        }
    }
}
